package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"git.drofa.ru/batushev.v/pdfcrc/pdf"
	"github.com/klippa-app/go-pdfium/requests"
	"github.com/klippa-app/go-pdfium/responses"
)

func openFile(filename string) (*responses.OpenDocument, func(), error) {
	openDocumentRequest := &requests.OpenDocument{}

	closeFile := func() {}

	file, err := os.Open(filename)
	if err != nil {
		return nil, nil, err
	}

	closeFile = func() {
		file.Close()
	}

	fileStat, err := file.Stat()
	if err != nil {
		return nil, closeFile, nil
	}

	openDocumentRequest.FileReader = file
	openDocumentRequest.FileReaderSize = fileStat.Size()

	if password != "" {
		openDocumentRequest.Password = &password
	}

	openedDocument, err := pdf.PdfiumInstance.OpenDocument(openDocumentRequest)
	if err != nil {
		return nil, closeFile, fmt.Errorf("could not open file with pdfium: %w", newPdfiumError(err))
	}

	originalCloseFile := closeFile
	closeFile = func() {
		pdf.PdfiumInstance.FPDF_CloseDocument(&requests.FPDF_CloseDocument{Document: openedDocument.Document})
		originalCloseFile()
	}

	return openedDocument, closeFile, nil
}

func readHashes(pageCount int) {
	f := filepath.Join(filepath.Dir(filePath), hashesFilename)
	data, err := os.ReadFile(f)
	if err != nil {
		hashes = make([]string, pageCount)
		return
	}
	hashes = strings.Split(string(data), hashDelimiter)
}

func writeHashes() error {
	f := filepath.Join(filepath.Dir(filePath), hashesFilename)
	return os.WriteFile(f, []byte(strings.Join(hashes, hashDelimiter)), 0666)
}

func isNotNumberSlice(s []string) bool {
	for _, v := range s {
		if _, err := strconv.Atoi(v); err != nil {
			errHandler(fmt.Errorf("В списке страниц страница %s не является числом", v), ExitCodeInvalidArguments)
			return true
		}
	}
	return false
}

func writeDifferentes() error {
	f := filepath.Join(filepath.Dir(filePath), diffFilename)
	return os.WriteFile(f, []byte(strings.Join(differentes, "\n")), 0666)
}

func normalizeRenderFormat() {
	renderFormat = strings.ToLower(strings.TrimSpace(renderFormat))
	if renderFormat != "jpeg" && renderFormat != "png" {
		renderFormat = "jpeg"
	}
}

func sByteFromSIntTwo(s []uint8, com bool) []byte {
	b := make([]byte, 0)
	for _, test := range s {
		b = strconv.AppendInt(b, int64(test), 10)
		if com {
			b = append(b, byte(','))
		}
	}
	return b
}
